package com.eqxiu.ieditor.commons.json;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.JavaType;

public class JsonMapper {

	//private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);

	private ObjectMapper mapper = null;
	private SerializationConfig seriConfig = null;

	private static JsonMapper jsonMapper = new JsonMapper();

	@SuppressWarnings("deprecation")
	private JsonMapper() {
		mapper = new ObjectMapper();
		seriConfig = mapper.getSerializationConfig();

		mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
		mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, false);
		mapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);

		mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
		// 返序列化时忽略不存在的属性
		mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		// 允许控制字符
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
		mapper.configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, false);
	}

	public static JsonMapper getInstance() {
		return jsonMapper;
	}

	/**
	 * 获取一个新的JsonMapper实例
	 * 
	 * @return
	 */
	public static JsonMapper newInstance() {
		return new JsonMapper();
	}

	public ObjectMapper getObjectMapper() {
		return this.mapper;
	}

	/**
	 * 针对对象添加过滤属性接口类
	 * 
	 * @param target
	 *            要过滤的对象类
	 * @param mixinSource
	 *            过滤接口类
	 */
	public JsonMapper addFilter(Class<?> target, Class<?> mixinSource) {
		seriConfig.addMixInAnnotations(target, mixinSource);
		return this;
	}

	/**
	 * Object可以是POJO，也可以是Collection或数组。 如果对象为Null, 返回"null". 如果集合为空集合, 返回"[]".
	 */
	public String toJson(Object object) {

		try {
			return mapper.writeValueAsString(object);
		} catch (IOException e) {
			e.printStackTrace();
			//logger.error("write to json string error: {} : {}", object, e.getLocalizedMessage());
			return "{}";
		}
	}

	/**
	 * 反序列化POJO或简单Collection如List<String>.
	 * 
	 * 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合.
	 * 
	 * 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String,JavaType)
	 * 
	 * @see #fromJson(String, JavaType)
	 */
	public <T> T fromJson(String jsonString, Class<T> clazz) {
		if (StringUtils.isEmpty(jsonString)) {
			return null;
		}

		try {
			return mapper.readValue(jsonString, clazz);
		} catch (IOException e) {
			e.printStackTrace();
			//logger.warn("parse json string error: {} :{}", jsonString, e.getLocalizedMessage());
			return null;
		}
	}

	public <T> T fromJson(String jsonStr, Class<?> collectionClass, Class<?>... elementClasses) {
		if (StringUtils.isEmpty(jsonStr)) {
			return null;
		}
		try {
			JavaType javaType = mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
			return mapper.readValue(jsonStr, javaType);
		} catch (IOException e) {
			e.printStackTrace();
			//logger.warn("parse json string error: {} : {}", jsonStr, e.getLocalizedMessage());
			return null;
		}
	}

}
